package client;
import java.io.IOException;
import java.net.ServerSocket;
import java.util.ArrayList;


/**
 * @author acidflow
 *
 */
public class ClientServer implements Runnable{
	
	private Client _client;
	private ArrayList<PeerConnection> _connections;
	private ServerSocket _serverSocket;
	private Thread _thread;
	private int _port;
	
	
	/**
	 * Crée la partie serveur du client pour accepter des connexions.
	 * @param port
	 * @param client
	 */
	public ClientServer(int port, Client client){
			_port = port;
			_connections = new ArrayList<PeerConnection>();
			_thread = new Thread(this, "Starting Client side Server");
			_client = client;
			_thread.start();
	}
	
	public ArrayList<String> getConnectedPeersToMyServer(){
		ArrayList<String> ret = new ArrayList<String>();
		for(int i = 0;  i <_connections.size(); i++){
			if(!_connections.get(i).get_socket().isClosed()){
				String str = _connections.get(i).get_socket().getInetAddress().toString() + ":"+ _connections.get(i).get_socket().getPort();
				ret.add(str);
			}
		}
		return ret;
	}

	/**
	 * Lance le thread gérant le serveur
	 */
	@Override
	public void run() {
		try {
			_serverSocket = new ServerSocket(_port);
			while(true){
				_client._SEMAPHORE_NB_CONNECTION_.acquire();
				PeerConnection pc = new PeerConnection(_serverSocket.accept(), _client);
				_connections.add(pc);
			//	System.out.println(_client._SEMAPHORE_NB_CONNECTION_.availablePermits());
			}
			
		} catch (IOException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
	}
}
